package com.luoyx.vjsb.authority.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.luoyx.vjsb.common.constant.ConstantCommon;
import com.luoyx.vjsb.common.holder.SpringContextHolder;
import com.luoyx.vjsb.core.entity.SysPermission;
import com.luoyx.vjsb.core.entity.SysRole;
import com.luoyx.vjsb.core.entity.SysRolePermission;
import com.luoyx.vjsb.core.entity.SysUser;
import com.luoyx.vjsb.core.service.ISysPermissionService;
import com.luoyx.vjsb.core.service.ISysRolePermissionService;
import com.luoyx.vjsb.core.service.ISysRoleService;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * shiro 工具
 * </p>
 *
 * @author luoyuanxiang <p>luoyuanxiang.github.io</p>
 * @since 2020/3/28 11:11
 */
public class UserUtil {


    /**
     * 通过用户获取角色
     *
     * @param user 1
     * @return 2
     */
    public static Set<String> getRoles(SysUser user) {
        Set<String> rolesSet;
        if (ConstantCommon.SUPPER_ADMIN.equals(user.getUsername())) {
            rolesSet = new HashSet<>(1);
            rolesSet.add("supper_admin");
        } else {
            rolesSet = new HashSet<>(1);
            if (user.getRoleId() == null) {
                return null;
            }
            SysRole byId = SpringContextHolder.getBean(ISysRoleService.class).getById(user.getRoleId());
            rolesSet.add(byId.getRoleName());
        }

        return rolesSet;
    }

    /**
     * 通过用户获取权限
     *
     * @param user 1
     * @return 2
     */
    public static Set<String> getPermissions(SysUser user) {
        if (ConstantCommon.SUPPER_ADMIN.equals(user.getUsername())) {
            List<SysPermission> list = SpringContextHolder.getBean(ISysPermissionService.class).list(new QueryWrapper<SysPermission>().isNotNull("permission"));
            Set<String> permissionsSet = new HashSet<>(list.size());
            list.forEach(sysPermission -> permissionsSet.add(sysPermission.getPermission()));
            return permissionsSet;
        } else {
            if (user.getRoleId() == null) {
                return null;
            }
            List<SysRolePermission> sysRolePermissions = SpringContextHolder.getBean(ISysRolePermissionService.class).list(new QueryWrapper<SysRolePermission>().eq("role_id", user.getRoleId()));
            List<String> ids = new ArrayList<>(sysRolePermissions.size());
            sysRolePermissions.forEach(sysRolePermission -> ids.add(sysRolePermission.getPermissionId()));
            List<SysPermission> sysPermissions = SpringContextHolder.getBean(ISysPermissionService.class).listByIds(ids);
            Set<String> permissionsSet = new HashSet<>(sysPermissions.size());
            sysPermissions.stream().filter(d -> d.getPermission() != null).forEach(d -> permissionsSet.add(d.getPermission()));
            return permissionsSet;
        }
    }
}
